package nickthissen.iracing.common;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.text.TextUtils;

import nickthissen.iracing.datamodels.Result;
import nickthissen.iracing.datamodels.StringResult;
import nickthissen.iracing.datamodels.User;
import nickthissen.iracing.networking.Networking;

/**
 * Created by Nick on 1-6-13.
 */
public class Messages
{
    public static void load(Context context)
    {
        Task<Void> t = new Task<Void>(context, loader);
        t.execute();
    }

    private static void showMessage(Context context, String message)
    {
        AlertDialog ad = new AlertDialog.Builder(context).create();
        ad.setCancelable(false);
        ad.setTitle("Attention!");
        ad.setMessage(message);
        ad.setButton(DialogInterface.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                dialog.dismiss();
            }
        });
        ad.show();
    }

    private static DataLoader<Void> loader = new DataLoader<Void>()
    {
        @Override
        public Result getData(Void in)
        {
            StringResult result = Networking.getMessage(this.getContext(), User.currentUser);
            if (result != null && result.Success)
            {
                return Result.ok(result.Object);
            }
            return Result.failed();
        }

        @Override
        public void onFinished(Result out)
        {
            if (out.Success && out.Object != null)
            {
                String msg = out.Object.toString();
                if (!TextUtils.isEmpty(msg))
                {
                    showMessage(this.getContext(), msg);
                }
            }
        }
    };
}
